package com.freezers.androidlogin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
/*import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;*/
import com.freezers.androidlogin.library.DatabaseHandler;
import com.freezers.androidlogin.library.JSONParser;

public class ImportDataActivity extends Activity{
	/*
	Button btnRegister;
	Button btnLinkToLogin;
	EditText inputFullName;
	EditText inputEmail;
	EditText inputPassword;
	TextView registerErrorMsg;
	
	// JSON Response node names
	private static String KEY_SUCCESS = "success";
	private static String KEY_ERROR = "error";
	private static String KEY_ERROR_MSG = "error_msg";
	private static String KEY_UID = "uid";
	private static String KEY_NAME = "name";
	private static String KEY_EMAIL = "email";
	private static String KEY_CREATED_AT = "created_at";

	
	
	
	
	
	
	
	   // Progress Dialog
  private ProgressDialog pDialog;
*/
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
 
    ArrayList<HashMap<String, String>> productsList;
 
    // url to get all products list
    private static String url_all_products = "http://91.190.43.115/android_clone/get_all_products.php";
 
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
   	//Product Table Column names
	private static final String TAG_PID = "pid";
	
	private static final String TAG_NAME = "name";
	private static final String TAG_PRICE = "price";
	private static final String TAG_DESCRIPTION = "description";
	private static final String TAG_CREATED_AT = "created_at";
    
    // products JSONArray
    JSONArray products = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.preparedb);
			// TODO Auto-generated method stub
			new ImportingData().execute();  		
		
					
						
					
	}
	
	/**
	 * Background Async Task to Load all product by making HTTP Request
	 * */

	class ImportingData extends AsyncTask<String, String, String> 
	{
		private ProgressDialog pDialog;
		   @Override
		    protected void onPreExecute() 
		    {
		        super.onPreExecute();
		        
		        
		    	//Starting dialog message
	            pDialog = new ProgressDialog(ImportDataActivity.this);
	            pDialog.setMessage("Importing Data. Please wait...");
	            pDialog.setIndeterminate(false);
	            pDialog.setCancelable(false);
	            pDialog.show();
			    }


		@Override
		protected String doInBackground(String... args) {
			// TODO Auto-generated method stub
			//return null;
			List<NameValuePair> params = new ArrayList<NameValuePair>();
            
            
            
            // getting JSON string from URL
                        
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
 
                       // Check your log cat for JSON response
          //  Log.d("All Products: ", json.toString());
          
            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
 
                if (success == 1) {
                	
                   	// products found
                    // Getting Array of Products
                	
                	
                	products = json.getJSONArray(TAG_PRODUCTS);
                	
                    // looping through All Products
                   /*
                	//for (int i = 0; i < products.length(); i++) {
                	   
                	//for (int i = 0; i < 1032; i++) {
                	int i = 0;
                	DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                	while (i < products.length()) {
                        JSONObject c = products.getJSONObject(i);
                        //Log.d("All Products: ", json.toString());
                        // Storing each json item in variable
                        String pid = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);
                        String price = c.getString(TAG_PRICE);
                        String description = c.getString(TAG_DESCRIPTION);
                        String created_at = c.getString(TAG_CREATED_AT);
                     
 
                    	// Store products in SQLite Database
						
                      
                     
						db.addProducts(pid, name, price, description, created_at);
						
						//db.close();
						i++;
						db.close();
					for (int i = 0; i < products.length(); i++) {
                	   
                	//for (int i = 0; i < 1032; i++) {
                	int i = 0;
                	DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                	while (i < products.length()) {
                        JSONObject c = products.getJSONObject(i);
                        //Log.d("All Products: ", json.toString());
                        // Storing each json item in variable
                        String pid = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);
                        String price = c.getString(TAG_PRICE);
                        String description = c.getString(TAG_DESCRIPTION);
                        String created_at = c.getString(TAG_CREATED_AT);
                     
 
                    	// Store products in SQLite Database
						
                      
                     
						db.addProducts(pid, name, price, description, created_at);
						
						//db.close();
						i++;
						db.close();
						
						*/
                	
                	DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                	Log.e("Msg","JSON get products");
            		
                //	for (int i = 0; i < products.length(); i++) {
                	int i = 0;
                	while (i < products.length()) {
                    	
                            JSONObject c = products.getJSONObject(i);
                                          
                         
                            //Log.d("All Products: ", json.toString());
                            // Storing each json item in variable
                          /*
                            String pid = c.getString(TAG_PID);
                            String name = c.getString(TAG_NAME);
                            String price = c.getString(TAG_PRICE);
                            String description = c.getString(TAG_DESCRIPTION);
                            String created_at = c.getString(TAG_CREATED_AT);
                                                    	// Store products in SQLite Database
    					*/
    						
    					//	db.addProducts(c.getString(TAG_PID), c.getString(TAG_NAME), c.getString(TAG_PRICE), c.getString(TAG_DESCRIPTION), c.getString(TAG_CREATED_AT));
                           // db.close();
                            //db.addProducts(pid, name, price, description, created_at);
                            db.addProducts(c.getString(TAG_PID), c.getString(TAG_NAME), c.getString(TAG_PRICE), c.getString(TAG_DESCRIPTION), c.getString(TAG_CREATED_AT));
                	i++;
                	}
                	//db.addProducts(pid, name, price, description, created_at)
                	//db.addProducts(TAG_PID, TAG_NAME, TAG_PRICE, TAG_DESCRIPTION, TAG_CREATED_AT);
                	
                	
                } else {
                   	// no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            //ImportDataActivity.class);
                    		RegisterActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
         
            //Closing dialog
            
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    pDialog.dismiss(); 
                }
            }, 0);
            Log.e("Msg","Beidzam importu");
			return null;
         
            //Closing Dialog
           // return null;
		}

	}
	
	

	
	
}
